/**
 * 
 * Copyright (c) 2011-2016, zzcmkj.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.cmkj.mine.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;

/**
 * 加密工具
 */
public class MyDigestUtils {

	private static MessageDigest digest = null;

	public static String encode64(String str) {
		try {
			return Base64.encodeBase64URLSafeString(str.getBytes("utf-8"));
		} catch (UnsupportedEncodingException e) {
		}
		return Base64.encodeBase64URLSafeString(str.getBytes());
	}

	public static String decode64(String str) {
		try {
			return new String(Base64.decodeBase64(str), "utf-8");
		} catch (UnsupportedEncodingException e) {
		}
		return new String(Base64.decodeBase64(str));
	}

	/**
	 * 加密密码
	 * 
	 * @author zzcmkj
	 * @param str
	 * @param key
	 * @return
	 */
	@SuppressWarnings("deprecation")
	public static String shaDigestForPasswrod(String str, String key) {
		return DigestUtils.shaHex(str + key);
	}

	@SuppressWarnings("deprecation")
	public static String shaDigestForPasswrod(String str) {
		return DigestUtils.shaHex(str + "zzcmkj");
	}

	public static final String hash(String data) {
		if (digest == null)
			try {
				digest = MessageDigest.getInstance("MD5");
			} catch (Exception e) {
				e.printStackTrace();
			}
		try {
			digest.update(data.getBytes("utf-8"));
		} catch (Exception e) {
		}
		return encodeHex(digest.digest());
	}

	public static final String encodeHex(byte bytes[]) {
		StringBuffer buf = new StringBuffer(bytes.length * 2);
		for (int i = 0; i < bytes.length; i++) {
			if ((bytes[i] & 0xff) < 16)
				buf.append("0");
			buf.append(Long.toString(bytes[i] & 0xff, 16));
		}

		return buf.toString();
	}

	public static void main(String[] args) throws Exception{
		System.out.println(MyDigestUtils.hash(MyDigestUtils.hash("a123456")));
	}
}
